package com.sk.weichat.ui;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.LinearLayout;

import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.DefaultRefreshFooterCreator;
import com.scwang.smartrefresh.layout.api.DefaultRefreshHeaderCreator;
import com.scwang.smartrefresh.layout.api.DefaultRefreshInitializer;
import com.scwang.smartrefresh.layout.api.RefreshFooter;
import com.scwang.smartrefresh.layout.api.RefreshHeader;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.sk.weichat.AppConfig;
import com.sk.weichat.AppConstant;
import com.sk.weichat.BuildConfig;
import com.sk.weichat.MyApplication;
import com.sk.weichat.R;
import com.sk.weichat.Reporter;
import com.sk.weichat.adapter.MessageLogin;
import com.sk.weichat.bean.ConfigBean;
import com.sk.weichat.bean.LoginAuto;
import com.sk.weichat.db.InternationalizationHelper;
import com.sk.weichat.db.dao.UserDao;
import com.sk.weichat.helper.DialogHelper;
import com.sk.weichat.helper.LoginHelper;
import com.sk.weichat.ui.account.LoginActivity;
import com.sk.weichat.ui.account.QuickLoginAuthority;
import com.sk.weichat.ui.account.RegisterActivity;
import com.sk.weichat.ui.account.SMSLoginActivity;
import com.sk.weichat.ui.base.BaseActivity;
import com.sk.weichat.ui.base.CoreManager;
import com.sk.weichat.util.AppUtils;
import com.sk.weichat.util.Constants;
import com.sk.weichat.util.DeviceInfoUtil;
import com.sk.weichat.util.EventBusHelper;
import com.sk.weichat.util.LogUtils;
import com.sk.weichat.util.PermissionUtil;
import com.sk.weichat.util.PreferenceUtils;
import com.sk.weichat.util.ToastUtil;
import com.sk.weichat.util.VersionUtil;
import com.sk.weichat.view.SelectionFrame;
import com.sk.weichat.view.TipDialog;
import com.xuan.xuanhttplibrary.okhttp.HttpUtils;
import com.xuan.xuanhttplibrary.okhttp.callback.BaseCallback;
import com.xuan.xuanhttplibrary.okhttp.result.ObjectResult;
import com.xuan.xuanhttplibrary.okhttp.result.Result;

import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import de.greenrobot.event.Subscribe;
import de.greenrobot.event.ThreadMode;
import okhttp3.Call;

/**
 * 启动页
 */
public class SplashActivity extends BaseActivity implements PermissionUtil.OnRequestPermissionsResultCallbacks {

    // 声明一个数组，用来存储所有需要动态申请的权限
    private static final int REQUEST_CODE = 0;
    private final Map<String, Integer> permissionsMap = new HashMap<>();

    private LinearLayout mSelectLv;
    private Button mSelectLoginBtn;
    private Button mSelectRegisBtn;

    // 配置是否成功
    private boolean mConfigReady = false;
    private SelectionFrame mTipDialog;

    public SplashActivity() {
        // 这个页面不需要已经获取config, 也不需要已经登录，
        noConfigRequired();
        noLoginRequired();

        // 定位权限等获取到配置再看是否要请求，
        // 照相
//        permissionsMap.put(Manifest.permission.CAMERA, R.string.permission_photo);
        // 麦克风
//        permissionsMap.put(Manifest.permission.RECORD_AUDIO, R.string.permission_microphone);
        // 手机状态
        permissionsMap.put(Manifest.permission.READ_PHONE_STATE, R.string.permission_phone_status);//手机号/imei
        // 存储权限,允许访问照片，媒体内容，文件
        permissionsMap.put(Manifest.permission.READ_EXTERNAL_STORAGE, R.string.permission_storage);
        permissionsMap.put(Manifest.permission.WRITE_EXTERNAL_STORAGE, R.string.permission_storage);
        //定位
        permissionsMap.put(Manifest.permission.ACCESS_COARSE_LOCATION, R.string.permission_location);
        permissionsMap.put(Manifest.permission.ACCESS_FINE_LOCATION, R.string.permission_location);
    }
    protected void hideBottomUIMenu() {
        //隐藏虚拟按键，并且全屏
        if (Build.VERSION.SDK_INT > 11 && Build.VERSION.SDK_INT < 19) { // lower api
            View v = this.getWindow().getDecorView();
            v.setSystemUiVisibility(View.GONE);
        } else if (Build.VERSION.SDK_INT >= 19) {
            Window _window = getWindow();
            WindowManager.LayoutParams params = _window.getAttributes();
            params.systemUiVisibility = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION|View.SYSTEM_UI_FLAG_IMMERSIVE;
            _window.setAttributes(params);
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {//暗色主题状态栏(白字)
            this.getWindow().getDecorView()
                    .setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_VISIBLE);
        }
        PreferenceUtils.putBoolean(this, "isBoot", false);
        Log.d("zxzx", "onCreate: " + SplashActivity.class.getSimpleName());
        LogUtils.log(getIntent());
        if ((getIntent().getFlags() & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
            finish();
            return;
        }
        // 如果不是任务栈第一个页面，就直接结束，显示上一个页面，
        // 主要是部分设备上Jitsi_pre页面退后台再回来会打开这个启动页flg=0x10200000，此时应该结束启动页，回到Jitsi_pre,
        if (!isTaskRoot()) {
            finish();
            return;
        }

        getWindow().setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS, WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
        setContentView(R.layout.activity_splash);
        // mStartTimeMs = System.currentTimeMillis();
        mSelectLv = (LinearLayout) findViewById(R.id.select_lv);
        mSelectLoginBtn = (Button) findViewById(R.id.select_login_btn);
        mSelectLoginBtn.setText(InternationalizationHelper.getString("JX_Login"));
        mSelectLoginBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(mContext, LoginActivity.class));
                finish();
            }
        });
        mSelectRegisBtn = (Button) findViewById(R.id.select_register_btn);
        mSelectRegisBtn.setText(InternationalizationHelper.getString("REGISTERS"));
        mSelectRegisBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(mContext, RegisterActivity.class));
            }
        });
        mSelectLv.setVisibility(View.INVISIBLE);

        // 注册按钮先隐藏，如果是接口返回开放注册再显示，
        mSelectRegisBtn.setVisibility(View.GONE);

        // 初始化配置
        new Thread(new Runnable() {
            @Override
            public void run() {
                initConfig();
            }
        }).start();

        // 同时请求定位以外的权限，

        EventBusHelper.register(this);
    }

    @Subscribe(threadMode = ThreadMode.MainThread)
    public void helloEventBus(MessageLogin message) {
        finish();
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionUtil.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms, boolean isAllGranted) {
        if (isAllGranted) {// 请求权限返回 已全部授权
            ready();
        }
    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms, boolean isAllDenied) {
        if (perms != null && perms.size() > 0) {
            // 用set去重，有的复数权限
            Set<String> tipSet = new HashSet<>();
            for (int i = 0; i < perms.size(); i++) {
                tipSet.add(getString(permissionsMap.get(perms.get(i))));
            }
            String tipS = TextUtils.join(", ", tipSet);
            boolean onceAgain = PermissionUtil.deniedRequestPermissionsAgain(this, perms.toArray(new String[perms.size()]));
            if(mTipDialog!=null){
                mTipDialog.dismiss();
                mTipDialog=null;
            }
             mTipDialog = new SelectionFrame(this);
            mTipDialog.setSomething(null, "为确保账号安全，使用悦聊前，需开启" + tipS + "权限，是否去开启", new SelectionFrame.OnSelectionFrameClickListener() {
                @Override
                public void cancelClick() {
                    System.exit(0);
                }

                @Override
                public void confirmClick() {
                    PermissionUtil.startApplicationDetailsSettings(SplashActivity.this, REQUEST_CODE);
                }
            });
           /* if (onceAgain) {// 部分 || 所有权限被拒绝且选择了（选择了不再询问 || 部分机型默认为不在询问）
                mTipDialog.setSomething(null, "为确保账号安全，使用悦聊前，需开启" + tipS + "权限，是否去开启", new SelectionFrame.OnSelectionFrameClickListener() {
                    @Override
                    public void cancelClick() {
                        System.exit(0);
                    }

                    @Override
                    public void confirmClick() {
                        PermissionUtil.startApplicationDetailsSettings(SplashActivity.this, REQUEST_CODE);
                    }
                });
            } else {// 部分 || 所有权限被拒绝
//                mTipDialog.setTip("为确保账号安全，使用悦聊前，需开启" + tipS + "权限，请退出悦聊后再次进入");
                mTipDialog.setSomething(null, "为确保账号安全，使用悦聊前，需开启" + tipS + "权限，是否去开启", new SelectionFrame.OnSelectionFrameClickListener() {
                    @Override
                    public void cancelClick() {
                        System.exit(0);
                    }

                    @Override
                    public void confirmClick() {
                        PermissionUtil.startApplicationDetailsSettings(SplashActivity.this, REQUEST_CODE);

                        System.exit(0);
                    }
                });
            }*/
            //设置点击屏幕不消失
            mTipDialog.setCanceledOnTouchOutside(false);
            //设置点击返回键不消失
            mTipDialog.setCancelable(false);
            mTipDialog.show();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE) {// 设置 手动开启权限 返回 再次判断是否获取全部权限
            ready();
        }
    }

    /**
     * 配置参数初始化
     */
    private void initConfig() {
        /*if (!MyApplication.getInstance().isNetworkActive()) {
            ToastUtil.showToast(SplashActivity.this, R.string.tip_get_config_failed);
            // 在断网的情况下，使用已经保存了的配置，
            ConfigBean configBean = coreManager.readConfigBean();
            setConfig(configBean);
            return;
        }*/

        getConfig();
    }

    private void getConfig() {
        String mConfigApi = AppConfig.readConfigUrl(mContext);

        Map<String, String> params = new HashMap<>();
        Reporter.putUserData("configUrl", mConfigApi);
        HttpUtils.get().url(mConfigApi)
                .params(params)
                .build()
                .execute(new BaseCallback<ConfigBean>(ConfigBean.class) {
                    @Override
                    public void onResponse(ObjectResult<ConfigBean> result) {
                        ConfigBean configBean;
                        if (result == null || result.getData() == null || result.getResultCode() != Result.CODE_SUCCESS) {
                            Log.e("zq", "获取网络配置失败，使用已经保存了的配置");
                            if (BuildConfig.DEBUG) {
                                ToastUtil.showToast(SplashActivity.this, R.string.tip_get_config_failed);
                            }
                            // 获取网络配置失败，使用已经保存了的配置，
                            configBean = coreManager.readConfigBean();
                        } else {
                            Log.e("zq", "获取网络配置成功，使用服务端返回的配置并更新本地配置");
                            configBean = result.getData();
                            if (!TextUtils.isEmpty(configBean.getAddress())) {
                                PreferenceUtils.putString(SplashActivity.this, AppConstant.EXTRA_CLUSTER_AREA, configBean.getAddress());
                            }
                            coreManager.saveConfigBean(configBean);
                            MyApplication.IS_OPEN_CLUSTER = configBean.getIsOpenCluster() == 1 ? true : false;
                        }
                        setConfig(configBean);
                    }

                    @Override
                    public void onError(Call call, Exception e) {
                        Log.e("zq", "获取网络配置失败，使用已经保存了的配置");
                        // ToastUtil.showToast(SplashActivity.this, R.string.tip_get_config_failed);
                        // 获取网络配置失败，使用已经保存了的配置，
                        ConfigBean configBean = coreManager.readConfigBean();
                        setConfig(configBean);
                    }
                });
    }

    private void setConfig(ConfigBean configBean) {
        if (configBean == null) {
            if (BuildConfig.DEBUG) {
                ToastUtil.showToast(this, R.string.tip_get_config_failed);
            }

            // 如果没有保存配置，也就是第一次使用，就连不上服务器，使用默认配置
            configBean = CoreManager.getDefaultConfig(this);
            if (configBean == null) {
                // 不可到达，本地assets一定要提供默认config,
                DialogHelper.tip(this, getString(R.string.tip_get_config_failed));
                return;
            }
            coreManager.saveConfigBean(configBean);
        }
        // 初始化配置
        if (coreManager.getConfig().isOpenRegister) {
            mSelectRegisBtn.setVisibility(View.VISIBLE);
        } else {
            mSelectRegisBtn.setVisibility(View.GONE);
        }
//        if (!coreManager.getConfig().disableLocationServer) {
//            // 定位
//            permissionsMap.put(Manifest.permission.ACCESS_COARSE_LOCATION, R.string.permission_location);
//            permissionsMap.put(Manifest.permission.ACCESS_FINE_LOCATION, R.string.permission_location);
//        }
        // 配置完毕
        mConfigReady = true;
        // 如果没有androidDisable字段就不判断，
        // 当前版本没被禁用才继续打开，
        if (TextUtils.isEmpty(configBean.getAndroidDisable()) || !blockVersion(configBean.getAndroidDisable(), configBean.getAndroidAppUrl())) {
            // 进入主界面
            ready();
        }
    }

    /**
     * 如果当前版本被禁用，就自杀，
     *
     * @param disabledVersion 禁用该版本以下的版本，
     * @param appUrl          版本被禁用时打开的地址，
     * @return 返回是否被禁用，
     */
    private boolean blockVersion(String disabledVersion, String appUrl) {
        String currentVersion = BuildConfig.VERSION_NAME;
        if (VersionUtil.compare(currentVersion, disabledVersion) > 0) {
            // 当前版本大于被禁用版本，
            return false;
        } else {
            // 通知一下，
            DialogHelper.tip(this, getString(R.string.tip_version_disabled));
            new TipDialog(this).setOnDismissListener(dialog -> {
                try {
                    Intent i = new Intent(Intent.ACTION_VIEW);
                    i.setData(Uri.parse(appUrl));
                    startActivity(i);
                } catch (Exception e) {
                    // 弹出浏览器失败的话无视，
                    // 比如没有浏览器的情况，
                    // 比如appUrl不合法的情况，
                }
                // 自杀，
                finish();
                MyApplication.getInstance().destory();
            });
            return true;
        }
    }

    private void ready() {
        if (!mConfigReady) {// 配置失败
            return;
        }

        // 检查 || 请求权限
        boolean hasAll = requestPermissions();
        if (hasAll) {// 已获得所有权限

            Uri linkAuth = getIntent().getData();
            if (linkAuth != null) {
                // 第三方网站请求登录
                quick(linkAuth);
            } else {
                jump();
            }
        }
    }

    private boolean requestPermissions() {
        return PermissionUtil.requestPermissions(this, REQUEST_CODE, permissionsMap.keySet().toArray(new String[]{}));
    }


    private void quick(Uri linkAuth) {

        String apikey = linkAuth.getQueryParameter("apiKey");
        String appSecret = linkAuth.getQueryParameter("appSecret");
        String url = linkAuth.getQueryParameter("url");

        Intent intent = new Intent(SplashActivity.this, QuickLoginAuthority.class);
        intent.putExtra("apiKey", apikey);
        intent.putExtra("appSecret", appSecret);
        intent.putExtra("url", url);

        Log.e("xuan", "quick: " + apikey + " , " + appSecret + " , " + url);

        startActivity(intent);
        finish();
    }

    @SuppressLint("NewApi")
    private void jump() {
        if (isDestroyed()) {
            return;
        }
        int userStatus = LoginHelper.prepareUser(mContext, coreManager);
        Intent intent = new Intent();
        switch (userStatus) {
            case LoginHelper.STATUS_USER_FULL:
            case LoginHelper.STATUS_USER_NO_UPDATE:
            case LoginHelper.STATUS_USER_TOKEN_OVERDUE:
                boolean login = PreferenceUtils.getBoolean(this, Constants.LOGIN_CONFLICT, false);
                if (login) {
                    intent.setClass(mContext, SMSLoginActivity.class);
                } else {
                    autoLogin();
                    return;
                }

                break;
            case LoginHelper.STATUS_USER_SIMPLE_TELPHONE:
                intent.setClass(mContext, SMSLoginActivity.class);
                break;
            case LoginHelper.STATUS_NO_USER:
            default:
                stay();
                return;// must return
        }
        startActivity(intent);
        finish();
    }

    /**
     * 自动登录检测token是否失效
     */
    public  void autoLogin(){
        Map<String, String> params = new HashMap<String, String>();
        params.put("access_token", coreManager.getSelfStatus().accessToken);
        params.put("userId", coreManager.getSelf().getUserId());
        params.put("serial", DeviceInfoUtil.getDeviceId(this));

        // 地址信息
        double latitude = MyApplication.getInstance().getBdLocationHelper().getLatitude();
        double longitude = MyApplication.getInstance().getBdLocationHelper().getLongitude();
        if (latitude != 0)
            params.put("latitude", String.valueOf(latitude));
        if (longitude != 0)
            params.put("longitude", String.valueOf(longitude));

        HttpUtils.get().url(coreManager.getConfig().USER_LOGIN_AUTO)
                .params(params)
                .build()
                .execute(new BaseCallback<LoginAuto>(LoginAuto.class) {
                    @Override
                    public void onResponse(ObjectResult<LoginAuto> result) {
                        Log.d(TAG, "onResponse() called with: result = [" + result + "]");
                        boolean success = com.sk.weichat.volley.Result.defaultParser(getApplicationContext(), result, false);

                        if (success) {//表示没有过期
                            Intent intent = new Intent();
                            intent.setClass(mContext, MainActivity.class);
                            startActivity(intent);
                            finish();
                            return;
                        }
                        MyApplication.getInstance().mUserStatus = LoginHelper.STATUS_USER_TOKEN_OVERDUE;
                        coreManager.logout();
                        // 弹出对话框
                        PreferenceUtils.putBoolean(getApplicationContext(), Constants.LOGIN_CONFLICT, true);
                        UserCheckedActivity.start(getApplicationContext());
                        finish();
                        overridePendingTransition(R.anim.anim_right_in,R.anim.up_out_anim);
                    }

                    @Override
                    public void onError(Call call, Exception e) {
                        Log.d(TAG, "onError() called with: call = [" + call + "], e = [" + e + "]");
                        MyApplication.getInstance().mUserStatus = LoginHelper.STATUS_USER_TOKEN_OVERDUE;
                        coreManager.logout();
                        // 弹出对话框
                        PreferenceUtils.putBoolean(getApplicationContext(), Constants.LOGIN_CONFLICT, true);
                        UserCheckedActivity.start(getApplicationContext());
                        finish();
                    }
                });
    }

    // 第一次进入酷聊，显示登录、注册按钮
    private void stay() {

        // 因为启动页有时会替换，无法做到按钮与图片的完美适配，干脆直接进入到登录页面
        startActivity(new Intent(mContext, SMSLoginActivity.class));
        overridePendingTransition(R.anim.up_show_anim, R.anim.up_out_anim);
        finish();
    }

}
